package com.wantupai.mvp.framework.support;


import com.wantupai.mvp.mvp.MvpPresenter;
import com.wantupai.mvp.mvp.MvpView;

/**
 * 代理模式-第二重代理-代理对象-绑定和解绑
 * 两个特点
 * 特点一：实现目标接口（可有可无）
 * 特点二：持有目标对象引用（必需）
 *
 * @param <V>
 * @param <P>
 * @author :zhangqing
 */
public class ProxyMvpDelegateCallBack<V extends MvpView, P extends MvpPresenter<V>> implements MvpDelegateCallback<V, P>
{

    private MvpDelegateCallback<V, P> mMvpCallback;

    public ProxyMvpDelegateCallBack(MvpDelegateCallback<V, P> mvpCallback)
    {
        mMvpCallback = mvpCallback;
    }
    @Override
    public P createPresenter()
    {
        P presenter = mMvpCallback.getPresenter();
        if (presenter == null)
        {
            presenter = mMvpCallback.createPresenter();
        }
        if (presenter == null)
        {
            throw new NullPointerException("presenter can not be null");
        }
        mMvpCallback.setPresenter(presenter);
        return presenter;
    }

    @Override
    public P getPresenter()
    {
        return mMvpCallback.getPresenter();
    }

    @Override
    public void setPresenter(P p)
    {
        mMvpCallback.setPresenter(p);
    }

    @Override
    public V getMvpView()
    {
        return mMvpCallback.getMvpView();
    }

    /**
     * 添加两个重要的方法
     */
    public void attach()
    {
        getPresenter().attach(getMvpView());
    }

    public void detach()
    {
        getPresenter().detach();
    }
}
